//
//  HomeViewController.m
//  笔记1
//
//  Created by  on 2022/11/3.
//

#import "HomeViewController.h"
#import "HomeHeader.h"
#import "HomeCell.h"
#import "SettingViewController.h"
#import "EditViewController.h"
#import "FileViewController.h"
#import "MoreViewController.h"
#import "NewFileViewController.h"
#import "SearchViewController.h"
#import "ImportViewController.h"

@interface HomeViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,  assign) NSInteger stamp;
@property (nonatomic, strong) UIButton *timeBtn;
@property (nonatomic, strong) NSMutableArray <Note *>*noteArray;
@property (nonatomic, strong) NSMutableArray <Note *>*fileArray;
@property (nonatomic, strong) NSMutableArray <Note *>*selectArray;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self loaddata];
}

- (void)initUI{
    self.backBtn.hidden = YES;
    UIBarButtonItem  *item1 = [self getbarbtn:@"搜索笔记" tag:301];
    UIBarButtonItem  *item2 = [self getbarbtn:@"设置" tag:302];
    self.navigationItem.rightBarButtonItems = @[item2,item1];
    
    self.timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.timeBtn.tag = 303;
    self.timeBtn.frame = CGRectMake(0, 0, 110, 30);
    [self.timeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [ self.timeBtn addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"下拉"]];
    img.frame = CGRectMake(self.timeBtn.frame.size.width + 4, 5, 14, 16);
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, StuBarHight + 5, 130, 30)];
    [view addSubview:self.timeBtn];
    [view addSubview:img];
    self.navigationItem.titleView = view;
    
    self.stamp = [[NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"] intValue];
    
    [self.collectionView registerNib:[HomeCell nib] forCellWithReuseIdentifier:[HomeCell ID]];
    [self.collectionView registerNib:[HomeHeader nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[HomeHeader ID]];
    self.collectionView.c_edges.equalTo(self.view);
}
- (UIBarButtonItem *)getbarbtn:(NSString *)icon tag:(NSInteger)tag{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, StuBarHight + 7, 30, 30)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = tag;
    btn.frame = CGRectMake(0,0, 30, 30);
    [btn addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[[UIImage imageNamed:icon] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    [view addSubview:btn];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:view];
    return item;
}
- (void)loaddata{
    self.noteArray = [NSMutableArray array];
    self.fileArray = [NSMutableArray array];
    [NoteTool find:self.stamp isFile:NO isDelete:NO complete:^(NSMutableArray<Note *> * _Nonnull result) {
        self.noteArray = [NSMutableArray arrayWithArray:result];
        [self.collectionView reloadData];
    }];
    [NoteTool find:self.stamp isFile:YES isDelete:NO complete:^(NSMutableArray<Note *> * _Nonnull result) {
        self.fileArray = [NSMutableArray arrayWithArray:result];
        [self.collectionView reloadData];
    }];
}
- (void)actionForBtn:(UIButton *)sender{
    [self action:sender.tag];
}
- (void)action:(NSInteger)tag{
    WS(self)
    if (tag == 301){
        SearchViewController *vc = [SearchViewController new];
        [self push:vc :YES];
    }else if (tag == 302){
        SettingViewController *vc = [SettingViewController new];
        [self push:vc :YES];
    }else if (tag == 303){
        JZBDateViewController *vc = [JZBDateViewController new];
        vc.stamp = self.stamp;
        vc.selectBlock = ^(int stamp) {
            weakself.stamp = stamp;
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
}
- (void)selectModel:(Note *)model{
    model.select = NO;
    MoreViewController *vc = [MoreViewController new];
    NSString *title = model.isFile ? @"导出":@"导入";
    vc.icons = @[@"编辑",@"导出",@"移到废纸篓"];
    vc.array = @[@"重命名",title,@"移到废纸篓"];
    vc.block = ^(NSString * _Nonnull title) {
        if ([title isEqualToString:@"重命名"]) {
            [InputViewController show:^(NSString * _Nonnull string) {
                model.name = string;
                [NoteTool update:model complete:^(BOOL success) {
                }];
            }];
        }else if ([title isEqualToString:@"导出"]){
            [NoteTool moveOutNote:model complete:^(BOOL success) {
                if (success==NO) {
                    [CCHud msg:LS(@"该文件夹还没有笔记")];
                }
                [self.collectionView reloadData];
            }];
        }else if ([title isEqualToString:@"导入"]){
            [NoteTool findFile:model.stamp isDelete:NO complete:^(NSMutableArray<Note *> * _Nonnull result) {
                if ( result == nil || result.count <= 0) {
                    return [CCHud msg:LS(@"还未创建任何文件夹")];
                }
                ImportViewController *vc = [ImportViewController new];
                vc.array = result;
                vc.model = model;
                [self presentViewController:vc animated:NO completion:nil];
            }];
        }else if ([title isEqualToString:@"移到废纸篓"]){
            model.isDelete = YES;
            [NoteTool update:model complete:^(BOOL success) {
            }];
        }else{
            model.select = NO;
            [self.collectionView reloadData];
        }
    };
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)setStamp:(NSInteger)stamp{
    _stamp = stamp;
    NSString *title = [NSDate transToDate:LS(@"yyyy年MM月") :stamp];
    [self.timeBtn setTitle:title forState:UIControlStateNormal];
    [self loaddata];
}
- (void)addNotify{
    [NotifyTool add:self :@selector(loaddata) :notifyNoteUpdate];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    WS(self);
    [SWTool swIMG:img type:ShiWuTypeOther success:^(NSDictionary * _Nonnull dict) {
        EditViewController *vc = [EditViewController new];
        Note *model = [Note new];
        [model.imgs addObject:data];
        model.stamp = [[NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"] integerValue];
        model.isFile = NO;
        model.account = APP.user.account;
        if ([dict isKindOfClass:[NSDictionary class]] &&
            [[dict valueForKey:@"result"] isKindOfClass:[NSArray class]]) {
            NSArray *array = dict[@"result"];
            NSDictionary *dc = array[0];
            model.name = dc[@"keyword"];
            model.content = dc[@"root"];
        }else{
            model.name = dict[@"keyword"];
            model.content = dict[@"root"];
        }
        vc.model = model;
        vc.isedit = YES;
        [weakself push:vc :YES];
        NSLog(@"=====%@",dict);
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.noteArray.count + self.fileArray.count + 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[HomeCell ID] forIndexPath:indexPath];
    WS(self)
    if (indexPath.row == 0) {
        cell.model = nil;
    }else if (indexPath.row <= self.noteArray.count){
        cell.model=self.noteArray[indexPath.row-1];
        cell.block = ^{
            [weakself selectModel:weakself.noteArray[indexPath.row - 1]];
        };
    }else{
        cell.model = self.fileArray[indexPath.row - self.noteArray.count - 1];
        cell.block = ^{
            [weakself selectModel:self.fileArray[indexPath.row - self.noteArray.count - 1]];
        };
    }
    return  cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    HomeHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[HomeHeader ID] forIndexPath:indexPath];
    NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"account"),bg_sqlValue(APP.user.account),bg_sqlKey(@"isFile"),bg_sqlValue(@(NO))];
    NSInteger count = [Note bg_count:nil where:where];
    header.content.text = [NSString stringWithFormat:LS(@"共%ld篇"),(long)count];
    return  header;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WS(self)
    if (indexPath.row == 0) {
        MoreViewController *vc = [MoreViewController new];
        vc.icons = @[@"笔记",@"文件夹_icon",@"扫描"];
        vc.array = @[@"笔记",@"文件夹",@"扫描"];
        vc.block = ^(NSString * _Nonnull title) {
            if ([title isEqualToString:@"笔记"]) {
                EditViewController *vc = [EditViewController new];
                Note *model = [Note new];
                model.account = APP.user.account;
                vc.model = model;
                vc.isedit = YES;
                [weakself push:vc :YES];
            }else if ([title isEqualToString:@"文件夹"]){
                NewFileViewController *vc = [NewFileViewController new];
                vc.block = ^(NSString * _Nonnull title) {
                    Note *model = [Note new];
                    model.name = title;
                    model.isFile = YES;
                    model.account = APP.user.account;
                    model.stamp = [[NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"] integerValue];
                    [NoteTool update:model complete:^(BOOL success) {
                        
                    }];
                };
                [self presentViewController:vc animated:NO completion:nil];
            }else if ([title isEqualToString:@"扫描"]){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [CCHud startHud];
                });
                UIImagePickerController *vc = [UIImagePickerController new];
                vc.delegate = weakself;
                vc.allowsEditing = YES;
                vc.sourceType = UIImagePickerControllerSourceTypeCamera;
                vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [weakself presentViewController:vc animated:YES completion:^{
                    [CCHud stopHud];
                }];
            }
        };
        [weakself presentViewController:vc animated:NO completion:nil];
    }else if (indexPath.row <= self.noteArray.count){
        EditViewController *vc = [EditViewController new];
        vc.model = self.noteArray[indexPath.row - 1];
        vc.isedit = NO;
        [self push:vc :YES];
    }else{
        FileViewController *vc = [FileViewController new];
        vc.model = self.fileArray[indexPath.row - self.noteArray.count - 1];
        vc.isadd = YES;
        [self push:vc :YES];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (SCREEN_WIDTH - 80) / 3;
    return  CGSizeMake(w, 140.0/92*w+42);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH ,191.0/353*SCREEN_WIDTH + 17.5);
}

@end
